package com.dahua.utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;

import com.dahua.bean.Msg;
import com.dahua.bean.ScanResult;
import com.dahua.bean.UpdateVersionBean;
import com.dahua.bean.User;
import com.dahua.bean.VersionBean;

public class HttpUtils {
    public static final String API_BASE_URL = Constants.API_URL;
    private final static int CONN_TIMEOUT = 8000;
    private static HttpParams httpParameters;
    private static List<NameValuePair> params;
    private Context context;

    static {
        httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, CONN_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpParameters, CONN_TIMEOUT);
    }

    private static HttpUtils manager;

    public static HttpUtils getInstance() {
        if (manager == null) {
            manager = new HttpUtils();
        }
        return manager;
    }

    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        if (info != null && info.isConnected())
            return true;
        else
            return false;
    }

    public void login(final Handler handler,
                      final String name, final String pwd) {
        ThreadPoolService.getInstance().submit(new Runnable() {
            public void run() {
                LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
                String urlString = API_BASE_URL + "logon.do?logonId="
                        + name + "&password=" + pwd;
                Message message = new Message();
                HttpGet httpRequest = new HttpGet(urlString);
                int code = 0;
                try {
                    HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
                    code = httpResponse.getStatusLine().getStatusCode();
                    if (code == 200) {
                        String strResult = EntityUtils
                                .toString(httpResponse.getEntity());
                        //System.out.println(strResult);
                        JSONObject jo = new JSONObject(strResult);
                        if ("1".equals(jo.optString("status"))) {
                            message.what = 1;
                            message.obj = jo;
                        } else {
                            message.what = 2;
                            message.obj = jo.optString("msg");
                        }
                    } else {
                        message.what = 2;
                        message.obj = "Network error,code:" + code;
                    }

                } catch (ClientProtocolException e) {
//                    e.printStackTrace();
                    message.what = 2;
                    message.obj = "Network error,code:" + code;
                } catch (IOException e) {
//                    e.printStackTrace();
                    message.what = 2;
                    message.obj = "Network error,code:" + code;
                } catch (Exception e) {
//                    e.printStackTrace();
                    message.what = 2;
                    message.obj = "Network error,code:" + code;
                }
                handler.sendMessage(message);
            }
        });
    }

    public void submit(final Handler handler,
                       final String code, final String userId) {
        ThreadPoolService.getInstance().submit(new Runnable() {
            public void run() {
                LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
                String urlString = API_BASE_URL + "scan.do?userId=" + userId + "&code=" + code;
                HttpGet httpRequest = new HttpGet(urlString);
                Message message = new Message();
                try {
                    HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
                    if (httpResponse.getStatusLine().getStatusCode() == 200) {
                        String strResult = EntityUtils.toString(httpResponse.getEntity());
                        // System.out.println(strResult);
                        JSONObject jo = new JSONObject(strResult);
                        if ("1".equals(jo.optString("status"))) {
                            JSONObject jo1 = jo.optJSONObject("object");
                            JSONArray ja = jo1.optJSONArray("results");
                            List<ScanResult> list = new ArrayList<ScanResult>();
                            for (int i = 0; i < ja.length(); i++) {
                                JSONObject jo2 = ja.getJSONObject(i);
                                ScanResult bean = new ScanResult();
                                bean.setModel(jo2.optString("model"));
                                bean.setStatus(jo2.optString("status"));
                                bean.setContent(jo2.optString("sn"));
                                bean.setError(jo2.optString("errorMsg"));
                                list.add(bean);
                            }
                            int failed = jo1.getInt("failed");
                            int success = jo1.getInt("success");
                            int totalIntegral = jo1.getInt("totalIntegral");
                            UserPreference.getInstance(context).setTotal(totalIntegral);
                            message.what = 1;
                            message.obj = list;
                            message.arg1 = success;
                            message.arg2 = failed;
                        } else {
                            message.what = 2;
                            message.obj = jo.optString("msg");
                        }
                    } else {
                        message.what = 2;
                        message.obj = "request error";
                    }
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                    message.what = 2;
                    message.obj = "No response,please check your network!";
                } catch (Exception e) {
                    e.printStackTrace();
                }
                handler.sendMessage(message);
            }
        });
    }

    public void getMsgNum(final Handler handler, final String userId) {
        ThreadPoolService.getInstance().submit(new Runnable() {
            public void run() {
                LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
                String urlString = API_BASE_URL + "home/config.do?userId=" + userId;
                HttpGet httpRequest = new HttpGet(urlString);
                Message message = new Message();
                try {
                    HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
                    if (httpResponse.getStatusLine().getStatusCode() == 200) {
                        String strResult = EntityUtils
                                .toString(httpResponse.getEntity());
                        //System.out.println(strResult);
                        JSONObject jo = new JSONObject(strResult);
                        Msg m = new Msg();
                        m.setMsgCounts(jo.optString("msgCounts"));
                        m.setModules(jo.optString("modules"));
                        message.what = 1;
                        message.obj = m;
                    } else {
                        message.what = 2;
                        message.obj = "request error";
                    }

                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                    message.what = 2;
                    message.obj = "No response,please check your network!";
                } catch (Exception e) {
                    e.printStackTrace();
                }
                handler.sendMessage(message);
            }
        });
    }

    public void getVersion(final Handler handler) {
        ThreadPoolService.getInstance().submit(new Runnable() {
            public void run() {
                //http://221.228.238.91:8888/servlet/api/apk/version.do
                LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
                String urlString = API_BASE_URL + "apk/version.do";
                HttpGet httpRequest = new HttpGet(urlString);
                Message message = new Message();
                try {
                    HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
                    if (httpResponse.getStatusLine().getStatusCode() == 200) {
                        String strResult = EntityUtils
                                .toString(httpResponse.getEntity());
                        System.out.println(strResult);
                        JSONObject jo = new JSONObject(strResult);
                        VersionBean m = new VersionBean();
                        m.setCode(jo.optString("versionCode"));
                        m.setDesc(jo.optString("updateDesc"));
                        m.setDownloadurl(jo.optString("downloadUrl"));
                        message.what = 10;
                        message.obj = m;
                    } else {
                        message.what = 2;
                        message.obj = "request error";
                    }

                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                    message.what = 2;
                    message.obj = "No response,please check your network!";
                } catch (Exception e) {
                    e.printStackTrace();
                }
                handler.sendMessage(message);
            }
        });
    }

    public void update(final Handler handler, final Context mcontext) {
        ThreadPoolService.getInstance().submit(new Runnable() {
            public void run() {
                //http://221.228.238.91:8888/servlet/api/apk/version.do
                LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
                String urlString = API_BASE_URL + "app/version.do";
                HttpGet httpRequest = new HttpGet(urlString);
                Message message = new Message();
                int code = 0;
                try {
                    HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
                    code = httpResponse.getStatusLine().getStatusCode();
                    if (code == 200) {
                        String strResult = EntityUtils.toString(httpResponse.getEntity());
                        // System.out.println(strResult);
                        JSONObject jo = new JSONObject(strResult);
                        UpdateVersionBean m = new UpdateVersionBean();
                        SharedPreferences userSettings = mcontext.getSharedPreferences("versioninfo", 0);
                        SharedPreferences.Editor editor = userSettings.edit();
                        editor.putString("version", jo.optString("ANDROID_VERSION"));
                        editor.putString("desc", jo.optString("ANDROID_UPDATE_DESC"));
                        editor.putString("uri", jo.optString("ANDROID_DOWNLOAD_URL"));
                        editor.commit();

                        m.setANDROID_VERSION(jo.optString("ANDROID_VERSION"));
                        m.setANDROID_DOWNLOAD_URL(jo.optString("ANDROID_DOWNLOAD_URL"));
                        m.setANDROID_UPDATE_DESC(jo.optString("ANDROID_UPDATE_DESC"));
                        m.setIOS_DOWNLOAD_URL(jo.optString("IOS_DOWNLOAD_URL"));
                        m.setIOS_UPDATE_DESC(jo.optString("IOS_UPDATE_DESC"));
                        m.setIOS_VERSION(jo.optString("IOS_VERSION"));
                        message.what = 10;
                        message.obj = m;
                    } else {
                        message.what = 2;
                        message.obj = "Network error,code:" + code;
                    }

                } catch (ClientProtocolException e) {
                    // e.printStackTrace();
                    message.what = 2;
                    message.obj = "Network error,code:" + code;
                } catch (IOException e) {
//                    e.printStackTrace();
                    message.what = 2;
                    message.obj = "Network error,code:" + code;
                } catch (Exception e) {
//                    e.printStackTrace();
                    message.what = 2;
                    message.obj = "Network error,code:" + code;
                }
                handler.sendMessage(message);
            }
        });
    }

}